/*******************************************************************************
* Copyright (c) 2012 
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* zhangliang - initial API and implementation
*******************************************************************************/

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include "config.h"
#include "singleton.h"

/*!
 * @brief
 *  an execution of some job, function prototype define
 * @return finish_flag
 *  false means one pass of the execution is finish but there're more to do
 *  true means all execution is finish and the funcion object can be removed
 *  from the job queue 
 */
typedef boost::function<bool (void)> Execution;

// thread pool
class ThreadPool : public Singleton<ThreadPool> {
 public:
  ThreadPool(void);

  void Run(uint32_t concurrency_hint = 0);

  // push job
  void Add(const Execution& execution);

  // stop
  void Finalize(void);

 private:
  void ThreadWork(void);

  // thread arrays, size is "cpu num" * 2 + 2
  boost::scoped_array<boost::thread> threads_;
  uint32_t concurrency_;
  // job queue, size is the same as the number of modules
  boost::circular_buffer<Execution> job_queue_;
  // condition_variable for notifying that there're jobs in queue
  boost::condition_variable wait_job_cond_;
  // mutex
  boost::mutex mutex_;
};


#endif // THREADPOOL_H

